package worker

import (
	"common/web"
	"github.com/gorilla/websocket"
	"xmediaEmu/pkg/cws"
	"xmediaEmu/pkg/cws/entity"
	"xmediaEmu/pkg/emulator/config"
	"xmediaEmu/pkg/log"
)

var (
	upgrader = &websocket.Upgrader{} // use default options
)

// Handler就是Manager角色.
type Handler struct {
	// service.RunnableService
	wsConn *websocket.Conn
	// Client that connects to coordinator
	oClient *cws.Client //ws连接.
	cfg     config.Config

	// TODO: 内部实例定义.

}

// 支持ws复用，gin 框架.
// ws的命令server只要一个通道即可.
func NewHandler(conf config.Config, conn *websocket.Conn) *Handler {
	return &Handler{
		wsConn: conn,
		cfg:    conf,
		// TODO: init here.
	}
}

// Run starts a Handler running logic
func (h *Handler) Run(serverId string) {
	h.oClient = cws.NewClient(serverId, web.NewWSocket(h.wsConn))
	h.routes()
	log.Logger.Debugf("[worker] connected from: %v", h.wsConn.RemoteAddr())

	// block here.
	h.oClient.Listen()
}

// client端收到响应后需要绑定对应ip和端口.
func (h *Handler) handleAsrStart() cws.PacketHandler {
	return func(resp cws.WSPacket) (req cws.WSPacket) {
		log.Logger.Info("Received a start request from XMedia")
		// TODO: 逻辑在这里处理.
		rom := entity.OpenShortAsr{}
		if err := rom.From(resp.Data); err != nil {
			return cws.EmptyPacket
		}

		//
		return cws.EmptyPacket
	}
}

// client端收到响应后需要绑定对应ip和端口.
func (h *Handler) handleAsrEnd() cws.PacketHandler {
	return func(resp cws.WSPacket) (req cws.WSPacket) {
		log.Logger.Info("Received a start request from XMedia")
		// TODO: 逻辑在这里处理.
		return cws.EmptyPacket
	}
}
